package com.itheima.kafka.stream;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.util.Arrays;
import java.util.Properties;

/**
 * 需求：
 *      接收kafka消息内容并计算输入消息内单词的个数
 *      如：
 *          hello kafka streams
 *          hello heima kafka
 *          hello shanghai heima kafka
 * 结果：
 *     hello 3
 *     kafka 3
 *     streams 1
 *     heima 2
 *     shanghai 1
 *
 * @Description:
 * @Version: V1.0
 */
public class KafkaStreamFastStart {
    private static final String TOPICIN = "itcast-topic-input";
    private static final String TOPICOUT = "itcast-topic-output";
    public static void main(String[] args) {
        //1 kafka配置信息
        Properties prop = new Properties();
        prop.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.129:9092");
        prop.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-sample");

        StreamsBuilder builder = new StreamsBuilder();
        group(builder);
        KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), prop);
        kafkaStreams.start();

    }

    private static void group(StreamsBuilder builder){
        KStream<String,String> stream = builder.stream(TOPICIN);
        stream.flatMapValues(new ValueMapper<String, Iterable<?>>() {
            @Override
            public Iterable<?> apply(String value) {
                System.out.println("消息内容"+value);
                return Arrays.asList(value.split(" "));
            }
        }).groupBy((key,value)->value)
                .windowedBy(TimeWindows.of(5000))
                .count().toStream()
                .map((key,value)->{
                    return new KeyValue<>(key.key().toString(),value.toString());
                }).to(TOPICOUT);
    }
}